package br.com.travesso.security.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import br.com.travesso.security.domain.Usuario;
import br.gov.frameworkdemoiselle.internal.producer.ResourceBundleProducer;
import br.gov.frameworkdemoiselle.util.ResourceBundle;

public class UsuarioDAO {

	private DBHelper dbHelper;

	private ResourceBundle bundle = ResourceBundleProducer
			.create("securityMessages");

	public UsuarioDAO(DBHelper dbHelper) {
		this.dbHelper = dbHelper;
	}

	/**
	 * Consulta um usuário no banco de dados a partir de seu LOGIN.
	 * 
	 * @param login
	 * @throws SQLException
	 * @throws Exception
	 */
	public Usuario buscarPorLogin(final String login) throws SQLException {

		PreparedStatement ps = null;
		ResultSet rs = null;
		ResultSet rsUsuario = null;
		Usuario user = null;

		Connection conn = dbHelper.getConnection();
		if (conn == null) {
			throw new SecurityException(
					bundle.getString("erro.acesso.banco.de.dados"));
		}
		try {
			final String sql = "SELECT u.* FROM " + Usuario.TABELA_USUARIO
					+ " u WHERE u." + Usuario.COLUNA_LOGIN + " = ?";
			ps = conn.prepareStatement(sql);
			ps.setString(1, login);
			rs = ps.executeQuery();
			if (rs.next()) {
				user = lerUsuarioDoResultSet(rs);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				if (null != rs) {
					rs.close();
				}
				if (null != rsUsuario) {
					rsUsuario.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
			try {
				if (null != ps) {
					ps.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}

		return user;
	}

	private Usuario lerUsuarioDoResultSet(final ResultSet rs)
			throws SQLException {
		Usuario user;
		user = new Usuario();
		user.setId(rs.getLong(Usuario.COLUNA_ID));
		user.setLogin(rs.getString(Usuario.COLUNA_LOGIN));
		user.setSenha(rs.getString(Usuario.COLUNA_SENHA));
		return user;
	}
}
